<script setup lang="ts">
import {Paperclip} from "@element-plus/icons-vue";
import {FilesCard,MentionSender} from "vue-element-plus-x";
import {ref} from 'vue'
import {type ChatInputDTO} from "./types";
import type {MentionOption} from "element-plus";
import FileUploader from "@/views/ai/agent/x6/com/file-upload-batch.vue";

const emits = defineEmits<{
  (e:'query',v:ChatInputDTO):void;
  (e:'rightChange'):void
}>();
const dto=ref<ChatInputDTO>({})
const uploader=ref<InstanceType<typeof FileUploader>>()
const options = ref<MentionOption[]>([
])
const senderRef=ref<InstanceType<typeof MentionSender>>()
const doSubmit=()=>{
  emits('query',dto.value)
  dto.value={}
}
const openFileUpload=()=>{
  senderRef.value?.openHeader()
  uploader.value?.open(true)
}
const delFile=(furl:string)=>{
  if (dto.value.files){
    dto.value.files=dto.value.files.filter(s=>s!==furl)
  }
  if (dto.value?.files?.length==0){
    senderRef.value?.closeHeader()
  }
}
const getFileName = (f: string) => {
  const pathname = new URL(f).pathname;
  const segments = pathname.split('/');
  return segments.pop() || '';
};
const onOk = (url:string) => {
  if (!dto.value.files){
    dto.value.files=[]
  }
  dto.value.files.push(url);
  uploader.value?.open(false)
};
const doOrderCheck=()=>{
  dto.value.query="请帮我进行合同审查"
  doSubmit()
}
</script>

<template>
  <MentionSender ref="senderRef"
                 @submit="doSubmit"
                 v-model="dto.query" placeholder="" variant="updown"
                 :trigger-strings="['#']"
                 :options="options"
                 clearable :auto-size="{minRows: 1, maxRows: 3}" allow-speech >
    <template #prefix>
      <div class="line5">
        <el-button @click="openFileUpload" round plain color="#626aef">
          <el-icon><Paperclip /></el-icon>
        </el-button>
      </div>
      <div>
<!--        <file-upload-batch ref="uploader" @ok="onOk"/>-->
        <file-uploader ref="uploader" @ok="onOk"/>
      </div>
    </template>
    <template #header>
      <div class="img-toolbar">
        <div v-for="(f,i) in dto.files" :key="i">
          <FilesCard img-variant="square" :url="f" :name="getFileName(f)" showDelIcon @delete="delFile(f)" />
        </div>
      </div>
      <div v-if="dto.files&&dto.files.length>0" style="padding: 10px">
        <el-button type="primary" size="small" round @click="doOrderCheck">合同审查</el-button>
      </div>
    </template>
  </MentionSender>
</template>

<style scoped lang="scss">
.sender_header{
  min-height: 200px;
  background-color: white;
}
.img-toolbar{
  display: flex;
  flex-direction: row;
  gap: 10px;
  padding: 10px;
}
</style>
